package com.kt.uokos.yimo.wx.controller;

import com.kt.uokos.yimo.dao.Keyword;
import com.kt.uokos.yimo.dao.SearchHistory;
import com.kt.uokos.yimo.service.KeyWordService;
import com.kt.uokos.yimo.service.SearchHistoryService;
import com.kt.uokos.yimo.util.ResponseUtil;
import com.kt.uokos.yimo.wx.annocation.LoginUser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/wx/search/")

public class WxSearchController {

    final int defaultId = 6;

    @Resource
    private KeyWordService keyWordService;

    @Resource
    private SearchHistoryService searchHistoryService;


    @GetMapping("index")
    public Object index(@LoginUser Integer userId){
        //拿到表中默认关键词
        Keyword defaultKeyword = keyWordService.queryDefault(defaultId);
        //拿到表中热门关键词
        List<Keyword> hotKeyword = keyWordService.queryHot();

        List<SearchHistory> keywordList;
        if (userId!=null){
            keywordList =  searchHistoryService.queryByUid(userId);
        }
        else {
            keywordList = new ArrayList<>(0);
        }

        HashMap<String , Object> map = new HashMap<>();
        map.put("defaultKeyword", defaultKeyword);
        map.put("historyKeywordList", keywordList);
        map.put("hotKeywordList", hotKeyword);
        return ResponseUtil.ok(map);
    }


    @GetMapping("helper")
    public Object helper(@NotEmpty String keyword,
                         @RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer limit) {
        List<Keyword> keywordsList = keyWordService.queryByKeyword(keyword, page, limit);
        String[] keys = new String[keywordsList.size()];
        int index = 0;
        for (Keyword key : keywordsList) {
            keys[index++] = key.getKeyword();
        }
        return ResponseUtil.ok(keys);
    }
}
